var map,onLoadGeocoderEvent, startOverlay, endOverlay;

function queryPoints() {

    var startLat = $('#start_lat').val();
    var startLon = $('#start_lon').val();
    var destLat = $('#destination_lat').val();
    var destLon = $('#destination_lon').val();

    console.log(startLat, startLon, destLat, destLon);

    if(startLat != '' && startLon != '') {
        var startGeocoder = new YMaps.Geocoder(new YMaps.GeoPoint(startLon, startLat), { results: 1});
        var startListener = YMaps.Events.observe(startGeocoder, startGeocoder.Events.Load, function () {
            if (this.found) {
                $('#fromName').parent().css('visibility', 'visible').end().text(this.get(0).text);
            }
            startListener.disable();
            startListener.cleanup();
        });
    }

    if(destLat != '' && destLon != '') {
        var destGeocoder = new YMaps.Geocoder(new YMaps.GeoPoint(destLon, destLat), { results: 1});
        var destListener = YMaps.Events.observe(destGeocoder, destGeocoder.Events.Load, function () {
            if (this.found) {
                $('#toName').parent().css('visibility', 'visible').end().text(this.get(0).text);
            }
            destListener.disable();
            destListener.cleanup();
        });
    }

}

function createMap(ctrId) {

    startOverlay =  new YMaps.Placemark(new YMaps.GeoPoint(0, 0), {style: "default#arrowRightIcon" });
    endOverlay =  new YMaps.Placemark(new YMaps.GeoPoint(0, 0), {style: "default#arrowLeftIcon" });


    map = new YMaps.Map(YMaps.jQuery("#" + ctrId)[0]);
    var geocoder = new YMaps.Geocoder("Ярославль");
    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (!this.found)
            map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);
        else
            map.setCenter(this.get(0).getCoordPoint(), 11, YMaps.MapType.MAP);

        map.addControl(new YMaps.TypeControl());
        map.addControl(new YMaps.Zoom());
        map.addControl(new YMaps.SearchControl());

        var toolbar = new YMaps.ToolBar([]);
        map.addControl(toolbar, new YMaps.ControlPosition(YMaps.ControlPosition.TOP_RIGHT, new YMaps.Point(5, 40)));

        var pickerFrom = new PointPickerControl(toolbar, "Откуда", startOverlay, function(point) {
            $('#start_lat').val(point.getLat());
            $('#start_lon').val(point.getLng());
            queryPoints();
        });

        var pickerTo = new PointPickerControl(toolbar, "Куда", endOverlay, function(point) {
            $('#destination_lat').val(point.getLat());
            $('#destination_lon').val(point.getLng());
            queryPoints();
        });

        map.addControl(pickerFrom);
        map.addControl(pickerTo);
        drawRoutes();
    });
}

var ovrStations = {};
var geoStations = {};
var ovrRoutes = {};

var toggle = true;

function drawRoutes() {
    var styles = {};

    var style = new YMaps.Style();
    style.lineStyle = new YMaps.LineStyle();
    style.lineStyle.strokeColor = "cc0000";
    style.lineStyle.strokeWidth = "4";
    YMaps.Styles.add("tram_line", style);
    styles["tram_line"] = style;

    style = new YMaps.Style();
    style.lineStyle = new YMaps.LineStyle();
    style.lineStyle.strokeColor = "0000cc";
    style.lineStyle.strokeWidth = "4";
    YMaps.Styles.add("trolley_line", style);
    styles["trolley_line"] = style;

    var style = new YMaps.Style();
    style.lineStyle = new YMaps.LineStyle();
    style.lineStyle.strokeColor = "00cc00";
    style.lineStyle.strokeWidth = "4";
    YMaps.Styles.add("bus_line", style);
    styles["bus_line"] = style;

    var style = new YMaps.Style();
    style.iconStyle = new YMaps.IconStyle();
    style.iconStyle.href = 'images/i-green-dot.png';
    style.iconStyle.size = new YMaps.Point(9, 9);
    style.iconStyle.offset = new YMaps.Point(-4, -8);
    YMaps.Styles.add("bus_st", style);
    styles["bus_st"] = style;

    var style = new YMaps.Style();
    style.iconStyle = new YMaps.IconStyle();
    style.iconStyle.href = 'images/i-red-dot.png';
    style.iconStyle.size = new YMaps.Point(9, 9);
    style.iconStyle.offset = new YMaps.Point(-4, -8);
    YMaps.Styles.add("tram_st", style);
    styles["tram_st"] = style;

    var style = new YMaps.Style();
    style.iconStyle = new YMaps.IconStyle();
    style.iconStyle.href = 'images/i-blue-dot.png';
    style.iconStyle.size = new YMaps.Point(9, 9);
    style.iconStyle.offset = new YMaps.Point(-4, -8);
    YMaps.Styles.add("trolley_st", style);
    styles["trolley_st"] = style;

    for (var i in info.routes) {
        var rt = info.routes[i];
        if (!rt.type)
            continue;

        for (var j = 1; j < rt.stations.length; j++) {
            var id = "" + rt.stations[j] + ":" + rt.stations[j - 1] + ":" + rt.type;
            if (ovrRoutes[id])
                continue;

            if (l1 = lines[rt.stations[j - 1]])
                if (l2 = l1[rt.stations[j]]) {
                    var line = YMaps.Polyline.fromEncodedPoints(l2[0], l2[1], {
                        style: styles[rt.type + "_line"],
                        draggable: false,
                        hasBalloon: false
                    });
                    ovrRoutes[id] = line;
                    //map.addOverlay(line);
                }
        }

        for (var j = 0; j < rt.stations.length; j++)
            for (var k in info.stations)
                if (info.stations[k].id == rt.stations[j]) {
                    var st = info.stations[k];

                    var id = "" + st.id + ":" + rt.type;
                    if (ovrStations[id])
                        continue;

                    var st = info.stations[k];
                    var geo = new YMaps.GeoPoint(st.lon, st.lat);
                    var ovr = new YMaps.Placemark(geo, {
                        style: styles[rt.type + "_st"],
                        draggable: false,
                        hasBalloon: false,
                        hasHint: true,
                    });
                    
                    if(st.name)
                      ovr.name = st.name;

                    var f = function(rtid) {
                        YMaps.Events.observe(ovr, ovr.Events.Click, function(ovr) {

                            if (toggle)
                                showSingleRoute(rtid);
                            else
                                showAll();

                            toggle = !toggle;
                        });
                    };
                    f(rt.id);

                    geoStations[id] = geo;
                    ovrStations[id] = ovr;
                    //map.addOverlay(ovr);
                }
    }

    showAll();
}

function hideAll() {
    for (var i in ovrStations)
        map.removeOverlay(ovrStations[i]);

    for (var i in ovrRoutes)
        map.removeOverlay(ovrRoutes[i]);
}

function showAll() {
    for (var i in ovrStations)
        map.addOverlay(ovrStations[i]);

    for (var i in ovrRoutes)
        map.addOverlay(ovrRoutes[i]);
}

function showSingleRoute(rtid) {
    hideAll();
    showRoute(rtid);
}

var toggle = 0;

function showRoute(rtid, from, to) {    
    console.log(rtid, from, to);
    for (var i in info.routes)
        if (info.routes[i].id == rtid) {
            var rt = info.routes[i];

            if (!rt.type)
                continue;

            var show = 0;
            if(!from)
              show = 1;

            for (var j in rt.stations) {              
                var sid = rt.stations[j];              

                //console.log(sid);

                if (j != 0)               
                  if(show)
                  {
                    var id = "" + rt.stations[j] + ":" + rt.stations[j - 1] + ":" + rt.type;              
                    map.addOverlay(ovrRoutes[id]);
                  }

                if(from)
                  if(from == sid)
                    show = 1;                    
                
                if(show)
                {
                  var id = "" + sid + ":" + rt.type;  
                  map.addOverlay(ovrStations[id]);
                }
                              
                if(to)
                  if(to == sid)
                    show = 0;
            }
        }
}

function updateMap(data)
{
  hideAll();
  if(!data.routes)
    return;
    
  for(var i in data.routes)
  {
    for(var j in data.routes[i].items)
    {
      var it = data.routes[i].items[j];
      for(var k in it.route_ids)
        showRoute(it.route_ids[k], it.start.id, it.end.id);   
    }
    break;
  }
}
